<template>
<div style="display: flex;flex-direction:column;align-items: center;">
   
    <iframe src="https://app.unlimitedai.chat/" style="width: 100%; height: 700px;border: none;" />
</div>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      userInput: '',
    };
  },
  methods: {
    extractThinkingContent(content) {
      const thinkStart = content.indexOf('<think>') + 6;
      const thinkEnd = content.indexOf('</think>');
      if (thinkStart > 0 && thinkEnd > thinkStart) {
        return content.substring(thinkStart, thinkEnd);
      }
      return '';
    },
    formatMessageContent(content) {
      return content.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    },
    async sendMessage() {
      if (!this.userInput.trim()) return;

      const timestamp = new Date().toLocaleTimeString();

      // 添加用户消息到聊天记录
      this.messages.push({
        role: 'user',
        content: this.userInput,
        timestamp,
        thinking: false,
      });

      try {
        // 使用 fetch API 发送请求并处理流式响应
        const url = 'http://localhost:11434/api/chat'; // 修改为本地8080端口
        const body = JSON.stringify({
          model: 'deepseek-r1:1.5b',
          messages: [
            ...this.messages,
            { role: 'user', content: this.userInput },
          ],
          stream: true,
        });

        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body,
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 处理流式响应
        const reader = response.body.getReader();
        let assistantContent = '';
        let done = false;

        while (!done) {
          const { value, done: readerDone } = await reader.read();
          done = readerDone;

          if (!done) {
            // 解码流数据
            const decoder = new TextDecoder('utf-8');
            const chunk = decoder.decode(value, { stream: true });

            // 解析 JSON 数据
            try {
              const jsonChunks = chunk.split('\n').map(str => str.trim()).filter(str => str);
              for (const jsonStr of jsonChunks) {
                const json = JSON.parse(jsonStr);
                if (json.message && json.message.content) {
                  assistantContent += json.message.content;

                  // 实时更新界面，仅更新助理的消息
                  const thinkingContent = this.extractThinkingContent(assistantContent);
                  if (this.messages.length > 0 && this.messages[this.messages.length - 1].role === 'assistant') {
                    this.messages[this.messages.length - 1].content = assistantContent;
                    this.messages[this.messages.length - 1].thinking = thinkingContent ? thinkingContent : null;
                  } else {
                    this.messages.push({
                      role: 'assistant',
                      content: assistantContent,
                      timestamp,
                      thinking: thinkingContent ? thinkingContent : null,
                    });
                  }
                  this.$forceUpdate(); // 强制更新界面

                  // 确保聊天框自动滚动到底部
                  const chatBox = document.getElementById('chatBox');
                  chatBox.scrollTop = chatBox.scrollHeight;
                }
              }
            } catch (error) {
              console.warn('Error parsing JSON chunk:', error);
            }
          }
        }

        // 流结束时，确保最终消息已添加
        if (assistantContent.trim()) {
          const thinkingContent = this.extractThinkingContent(assistantContent);
          if (this.messages.length > 0 && this.messages[this.messages.length - 1].role === 'assistant') {
            this.messages[this.messages.length - 1].content = assistantContent;
            this.messages[this.messages.length - 1].thinking = thinkingContent ? thinkingContent : null;
          } else {
            this.messages.push({
              role: 'assistant',
              content: assistantContent,
              timestamp,
              thinking: thinkingContent ? thinkingContent : null,
            });
          }

          // 确保聊天框自动滚动到底部
          const chatBox = document.getElementById('chatBox');
          chatBox.scrollTop = chatBox.scrollHeight;
        }

      } catch (error) {
        console.error('Error sending message:', error);
        this.messages.push({
          role: 'assistant',
          content: 'Error: Unable to fetch response.',
          timestamp: new Date().toLocaleTimeString(),
          thinking: null,
        });
      }

      // 清空用户输入
      this.userInput = '';
    },
  },
};
</script>

<style lang="scss" scoped></style>
<!-- <template>
  <div class="chat-container">
    <div class="chat-box" id="chatBox">
      <div v-for="(message, index) in messages" :key="index" class="message">
        <div class="message-header">
          <span class="message-role">{{ message.role === 'user' ? 'You' : 'Assistant' }}</span>
          <span class="message-time">{{ message.timestamp }}</span>
        </div>
        <div :class="['message-content', { 'user-message': message.role === 'user' }]">
          <div v-if="message.thinking" class="thinking-bubble">
            <span class="thinking-tag">&lt;think&gt;</span>
            <span class="thinking-content">{{ message.thinking }}</span>
            <span class="thinking-tag">&lt;/think&gt;</span>
          </div>
          <div v-html="formatMessageContent(message.content)"></div>
        </div>
      </div>
    </div>
    <div class="input-box">
      <input
        v-model="userInput"
        placeholder="Type your message here..."
        @keyup.enter="sendMessage"
      />
      <button @click="sendMessage">Send</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      userInput: '',
    };
  },
  methods: {
    extractThinkingContent(content) {
      const thinkStart = content.indexOf('<think>') + 6;
      const thinkEnd = content.indexOf('</think>');
      if (thinkStart > 0 && thinkEnd > thinkStart) {
        return content.substring(thinkStart, thinkEnd);
      }
      return '';
    },
    formatMessageContent(content) {
      return content.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    },
    async sendMessage() {
      if (!this.userInput.trim()) return;

      const timestamp = new Date().toLocaleTimeString();

      // 添加用户消息到聊天记录
      this.messages.push({
        role: 'user',
        content: this.userInput,
        timestamp,
        thinking: false,
      });

      try {
        // 使用 fetch API 发送请求并处理流式响应
        const url = 'http://localhost:11434/api/chat'; // 修改为本地8080端口
        const body = JSON.stringify({
          model: 'deepseek-r1:1.5b',
          messages: [
            ...this.messages,
            { role: 'user', content: this.userInput },
          ],
          stream: true,
        });

        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body,
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 处理流式响应
        const reader = response.body.getReader();
        let assistantContent = '';
        let done = false;

        while (!done) {
          const { value, done: readerDone } = await reader.read();
          done = readerDone;

          if (!done) {
            // 解码流数据
            const decoder = new TextDecoder('utf-8');
            const chunk = decoder.decode(value, { stream: true });

            // 解析 JSON 数据
            try {
              const jsonChunks = chunk.split('\n').map(str => str.trim()).filter(str => str);
              for (const jsonStr of jsonChunks) {
                const json = JSON.parse(jsonStr);
                if (json.message && json.message.content) {
                  assistantContent += json.message.content;

                  // 实时更新界面，仅更新助理的消息
                  const thinkingContent = this.extractThinkingContent(assistantContent);
                  if (this.messages.length > 0 && this.messages[this.messages.length - 1].role === 'assistant') {
                    this.messages[this.messages.length - 1].content = assistantContent;
                    this.messages[this.messages.length - 1].thinking = thinkingContent ? thinkingContent : null;
                  } else {
                    this.messages.push({
                      role: 'assistant',
                      content: assistantContent,
                      timestamp,
                      thinking: thinkingContent ? thinkingContent : null,
                    });
                  }
                  this.$forceUpdate(); // 强制更新界面

                  // 确保聊天框自动滚动到底部
                  const chatBox = document.getElementById('chatBox');
                  chatBox.scrollTop = chatBox.scrollHeight;
                }
              }
            } catch (error) {
              console.warn('Error parsing JSON chunk:', error);
            }
          }
        }

        // 流结束时，确保最终消息已添加
        if (assistantContent.trim()) {
          const thinkingContent = this.extractThinkingContent(assistantContent);
          if (this.messages.length > 0 && this.messages[this.messages.length - 1].role === 'assistant') {
            this.messages[this.messages.length - 1].content = assistantContent;
            this.messages[this.messages.length - 1].thinking = thinkingContent ? thinkingContent : null;
          } else {
            this.messages.push({
              role: 'assistant',
              content: assistantContent,
              timestamp,
              thinking: thinkingContent ? thinkingContent : null,
            });
          }

          // 确保聊天框自动滚动到底部
          const chatBox = document.getElementById('chatBox');
          chatBox.scrollTop = chatBox.scrollHeight;
        }

      } catch (error) {
        console.error('Error sending message:', error);
        this.messages.push({
          role: 'assistant',
          content: 'Error: Unable to fetch response.',
          timestamp: new Date().toLocaleTimeString(),
          thinking: null,
        });
      }

      // 清空用户输入
      this.userInput = '';
    },
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
  overflow: hidden;
}

.chat-box {
  height: 80vh;
  overflow-y: auto;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin: 10px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.message {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.message-role {
  font-weight: bold;
}

.message-time {
  color: #999;
}

.message-content {
  padding: 8px;
  border-radius: 5px;
  background-color: #f0f0f0;
  line-height: 1.4;
}

.user-message {
  background-color: #d1eaff;
  text-align: right;
}

.thinking-bubble {
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 5px 8px;
  margin: 5px 0;
  font-style: italic;
  color: #666;
  display: inline-block;
}

.thinking-tag {
  color: #ff4d4f;
  font-weight: bold;
}

.input-box {
  display: flex;
  padding: 10px;
  border-top: 1px solid #eee;
}

.input-box input {
  flex: 1;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.input-box button {
  margin-left: 10px;
  padding: 10px 20px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-box button:hover {
  background-color: #40a9ff;
}
</style> -->
